
import {SyncHook, AsyncParallelHook } from 'tapable'
import { writeFile } from 'node:fs/promises';
import { join } from 'node:path'
import { mkdirSync } from 'node:fs'

type Hooks={
    onRuntimeFiles:SyncHook<[]>
    onLog:SyncHook<[string]>
}

type Plugin=(hooks:Hooks)=>void

//创建类
class Service {
    hooks:Hooks

    constructor(plugins:Array<Plugin>) {
        this.hooks = {
             onRuntimeFiles: new SyncHook(),
             onLog: new SyncHook(['message']),
        };
        
        if (plugins && plugins.length > 0) {
            plugins.forEach(plugin => plugin.call(this,this.hooks));
        }
        
    }

    run(){
       this.hooks.onLog.call('run')
       this.hooks.onRuntimeFiles.call()
    }

    register(plugin:Plugin){
       plugin.call(this,this.hooks)
    }
}

 
function myPlugin(options){
  return (hook:Hooks)=>{
        hook.onRuntimeFiles.tap('map',()=>{
            const path = process.cwd() + `/.qps/${options.name}`;
            mkdirSync(path, { recursive: true });
            writeFile(join(path, `./${options.fileName}`), options.content);
        })
   }
}



const service=new Service([])
service.register(myPlugin({
    name: 'plugin-model',
    fileName: '1.js',
    content: 'export const add=(a,b)=>{ return a+b }'
  }))
service.run()

